package com.stations.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.stations.register.AbstractServerInfos;
import com.stations.register.LinuxServerInfos;
import com.stations.register.TProjectActivation;
import com.stations.register.WindowsServerInfos;
import de.schlichtherle.license.LicenseContentException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * SystemInfoUtils 获取安装机相关信息
 *
 * @author bh_ljy
 * @version 2023/10/27 15:26
 **/
@Slf4j
public class SystemInfoUtils {

    public static void checkLicense(String data) throws Exception {
        String decrypt = RSAUtils.decrypt(data);
        TProjectActivation licenseCheckModel = JSONUtil.toBean(decrypt, TProjectActivation.class);
        //当前服务器真实的参数信息
        TProjectActivation serverCheckModel = SystemInfoUtils.getServerInfos();

        if (licenseCheckModel != null && serverCheckModel != null) {
            if (1 == licenseCheckModel.getIpCheckFlag()) {
                //校验IP地址
                if (checkIP(licenseCheckModel.getIpAddress(), serverCheckModel.getIpAddress())) {
                    throw new LicenseContentException("当前服务器的IP没在授权范围内");
                }
            }

            if (1 == licenseCheckModel.getMacCheckFlag()) {
                //校验Mac地址
                if (checkIP(licenseCheckModel.getMacAddress(), serverCheckModel.getMacAddress())) {
                    throw new LicenseContentException("当前服务器的Mac地址没在授权范围内");
                }
            }

            if (1 == licenseCheckModel.getBoardCheckFlag()) {
                //校验主板序列号
                if (checkSerial(licenseCheckModel.getMainBoardSerial(), serverCheckModel.getMainBoardSerial())) {
                    throw new LicenseContentException("当前服务器的主板序列号没在授权范围内");
                }
            }
            if (1 == licenseCheckModel.getCpuCheckFlag()) {
                //校验CPU序列号
                if (checkSerial(licenseCheckModel.getCpuSerial(), serverCheckModel.getCpuSerial())) {
                    throw new LicenseContentException("当前服务器的CPU序列号没在授权范围内");
                }
            }

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            final Date now = new Date();
            final Date notBefore = simpleDateFormat.parse(licenseCheckModel.getEnbaledate());
            final Date notAfter = simpleDateFormat.parse(licenseCheckModel.getExpiredate());
            if (null != notBefore && null != notAfter && now.before(notBefore)) {
                log.error("授权时间还未到");
                throw new LicenseContentException("授权时间还未到");
            }
            if (null != notAfter && now.after(notAfter)) {
                log.error("授权时间已过期,请联系厂商激活");
                throw new LicenseContentException("授权时间已过期,请联系厂商激活");
            }
            long l = DateUtil.betweenDay(now, notAfter, false);
            log.info("----------------系统剩余激活天数: [{}]", l);
        } else {
            throw new LicenseContentException("不能获取服务器硬件信息");
        }
    }

    /**
     * 校验当前服务器的IP/Mac地址是否在可被允许的IP范围内<br/>
     * 如果存在IP在可被允许的IP/Mac地址范围内，则返回true
     *
     * @return boolean
     */
    private static boolean checkIP(String expectedList, String serverList) {
        if (expectedList != null && !expectedList.isEmpty()) {
            if (serverList != null && !serverList.isEmpty()) {
                for (String expected : expectedList.split(",")) {
                    if (serverList.contains(expected.trim())) {
                        return false;
                    }
                }
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 校验当前服务器硬件（主板、CPU等）序列号是否在可允许范围内
     *
     * @return boolean
     */
    private static boolean checkSerial(String expectedSerial, String serverSerial) {
        if (org.apache.commons.lang3.StringUtils.isNotBlank(expectedSerial)) {
            if (StringUtils.isNotBlank(serverSerial)) {
                return !expectedSerial.equals(serverSerial);
            }

            return true;
        } else {
            return false;
        }
    }

    public static TProjectActivation getServerInfos() {
        //操作系统类型
        String osName = System.getProperty("os.name").toLowerCase();
        AbstractServerInfos abstractServerInfos;

        //根据不同操作系统类型选择不同的数据获取方法
        if (osName.startsWith("windows")) {
            abstractServerInfos = new WindowsServerInfos();
        } else if (osName.startsWith("linux")) {
            abstractServerInfos = new LinuxServerInfos();
        } else {//其他服务器类型
            abstractServerInfos = new LinuxServerInfos();
        }
        return abstractServerInfos.getServerInfos();
    }

}
